package servlet.admin;

import entity.AdoptAnimal;
import service.AdoptService;
import service.Impl.AdoptServiceImpl;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

@WebServlet(urlPatterns = "/admin/AdoptFindByTime")
public class AdoptFindByTimeServlet extends HttpServlet {
    private AdoptService adoptService = new AdoptServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String adoptTimeStr = req.getParameter("adoptTime");
        LocalDate adoptTime = LocalDate.parse(adoptTimeStr);

        List<AdoptAnimal> adoptList = adoptService.findByAdoptTime(adoptTime);
        JSONObject jsonResponse = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        for (AdoptAnimal adopt : adoptList) {
            JSONObject jsonAdopt = new JSONObject();
            jsonAdopt.put("id", adopt.getId());
            jsonAdopt.put("userName", adopt.getUser().getUserName());
            jsonAdopt.put("petName", adopt.getPet().getPetName());
            jsonAdopt.put("adoptTime", adopt.getAdoptTime());
            jsonAdopt.put("state", adopt.getState());
            jsonArray.put(jsonAdopt);
        }

        jsonResponse.put("success", true);
        jsonResponse.put("adoptList", jsonArray);

        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(jsonResponse.toString());
    }
}